<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElCheckbox } from 'element-plus'
import { ArrowDown, ShoppingCart, StarFilled } from '@element-plus/icons-vue'
import { cartGetInfo, caetDel, cartAddItem } from '@/api/cart'
import { orderPost } from '@/api/order'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { useOrderStore } from '@/stores'

const userStore = useUserStore()
const orderStore = useOrderStore()
const router = useRouter()
const name = ref()
const cartItems = ref([])
const isItem = ref(false)
const isAllSelected = ref(false)
const discount = ref(19.43)

const getCart = async () => {
  const res = await cartGetInfo()
  cartItems.value = res.data.map((item) => ({
    ...item,
    isSelected: false // 添加选中状态
  }))
  userStore.setNum(cartItems.value.length)
  if (cartItems.value.length === 0) {
    isItem.value = true
  }
}

onMounted(() => {
  name.value = userStore.user.username || '亲，请登录'
  getCart()
})

const increaseQuantity = async (id) => {
  const item = cartItems.value.find((item) => item.id === id)
  if (item) {
    item.num += 1
  }
  await cartAddItem({ num: item.num, id: item.id })
}

const decreaseQuantity = (id) => {
  const item = cartItems.value.find((item) => item.id === id)
  if (item && item.num > 1) {
    item.num -= 1
  }
}

const removeItem = async (id) => {
  await caetDel(id)
  ElMessage({
    message: '删除商品成功',
    type: 'success'
  })
  getCart()
}

const removeSelectedItems = async () => {
  await Promise.all(
    selectedItems.value.map(async (id) => {
      await caetDel(id)
    })
  )
  ElMessage({
    message: '删除选中商品成功',
    type: 'success'
  })
  getCart()
  selectedItems.value = []
}

const main = () => {
  router.push('/')
}

const getTotalQuantity = () => {
  return cartItems.value.reduce((total, item) => total + item.num, 0)
}

const toggleAllSelection = () => {
  if (isAllSelected.value) {
    cartItems.value.forEach((item) => (item.isSelected = true))
  } else {
    cartItems.value.forEach((item) => (item.isSelected = false))
  }
}

const selectedItemsCount = computed(() => {
  return cartItems.value.filter((item) => item.isSelected).length
})

const selectedItems = computed(() => {
  return cartItems.value.filter((item) => item.isSelected)
})

const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.price * item.num, 0) / 100
})

const discountAmount = computed(() => {
  // 添加折扣逻辑，假设有一个折扣金额
  return discount.value
})

const discountedPrice = computed(() => {
  return totalPrice.value - discountAmount.value
})

const itemDetail = ref(selectedItems)

const checkout = async () => {
  if (selectedItems.value.length > 0) {
    console.log(selectedItems.value)

    const allItem = ref({
      addressId: 60,
      paymentType: '003',
      details: itemDetail.value
    })

    const res = await orderPost(allItem.value)
    // console.log(allItem.value)
    orderStore.setOrder(res.data)
    router.push('/pay')
    ElMessage({
      message: '下单成功',
      type: 'success'
    })
  } else {
    ElMessage({
      message: '请选择要结算的商品',
      type: 'warning'
    })
  }
}
</script>

<template>
  <div class="container">
    <div class="taobao-header">
      <div class="top-bar">
        <span>中国大陆</span><el-icon class="xia"><ArrowDown /></el-icon>
        <span class="highlight" @click="login">{{ name }}</span>
        <span>免费注册</span>
        <span>手机逛淘宝</span>
        <span>网页无障碍</span>
        <span class="separator">|</span>
        <span @click="main" style="cursor: pointer">微购首页</span>
        <span>我的淘宝</span><el-icon class="xia"><ArrowDown /></el-icon>
        <span @click="cart">
          <el-icon class="shop"><ShoppingCart /></el-icon>购物车
        </span>
        <el-icon><StarFilled /></el-icon><span>收藏夹</span><el-icon class="xia"><ArrowDown /></el-icon>
        <span>商品分类</span>
        <span>免费开店</span><el-icon class="xia"><ArrowDown /></el-icon>
        <span
          >千牛卖家中心<el-icon class="xia"><ArrowDown /></el-icon
        ></span>
        <span>帮助中心</span><el-icon class="xia"><ArrowDown /></el-icon>
      </div>

      <div class="head-container">
        <div class="logo-search-nav">
          <div class="logo">
            <img src="@/assets/logo.png" alt="logo" class="logo-img" @click="main" />
          </div>
          <div class="cart-text">购物车</div>
        </div>
      </div>
    </div>

    <div v-if="isItem">购物车为空</div>

    <div v-else>
      <div class="cart-container">
        <div class="cart-header">
          <span>商品总数（{{ getTotalQuantity() }}）</span>
        </div>
        <div class="cart-controls">
          <el-checkbox v-model="isAllSelected" @change="toggleAllSelection">全选</el-checkbox>
          <button @click="removeSelectedItems">删除</button>
        </div>
        <div class="cart-item" v-for="item in cartItems" :key="item.id">
          <el-checkbox v-model="item.isSelected"></el-checkbox>
          <img :src="item.image" alt="商品图片" />
          <div class="details">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-spec">{{ item.spec }}</div>
          </div>
          <div class="item-actions">
            <span class="price">¥{{ (item.price / 100).toFixed(2) }}</span>
            <div class="custom-input-number">
              <span class="el-input-number__decrease" @click="decreaseQuantity(item.id)">-</span>
              <input type="text" class="el-input-number__input" v-model="item.num" readonly />
              <span class="el-input-number__increase" @click="increaseQuantity(item.id)">+</span>
            </div>
            <button @click="removeItem(item.id)">删除</button>
          </div>
        </div>
        <div class="cart-summary">
          <div class="summary-title">结算明细 已选 {{ selectedItemsCount }} 件商品</div>
          <div v-if="selectedItemsCount === 0" class="summary-content" style="font-size: large; margin-left: 70px; margin-top: 80px; margin-bottom: 67px">还没有待结算的商品</div>
          <div v-else class="summary-content">
            <div class="summary-images">
              <img v-for="item in selectedItems" :src="item.image" :key="item.id" class="summary-image" />
            </div>
            <div class="summary-content">商品总价: ¥{{ totalPrice.toFixed(2) }}</div>
            <div class="discount">
              共减: <span class="discount-amount">¥{{ discountAmount.toFixed(2) }}</span>
            </div>
          </div>
          <div class="total">
            合计: <span>¥{{ selectedItemsCount === 0 ? 0 : discountedPrice.toFixed(2) }}</span>
          </div>
          <button class="checkout-button" @click="checkout">结算</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  padding: 0 95px;
}

.taobao-header {
  width: 100%;
  background-color: #f5f5f5;
}

.top-bar {
  display: flex;
  justify-content: flex-start;
  background-color: #e8e6e2;
  padding: 5px 10px;
  border-bottom: 1px solid #eee;
}

.top-bar span {
  margin-right: 8px;
  color: #666;
  font-size: 12.5px;
}
.top-bar .highlight {
  color: red;
}

.top-bar .separator {
  color: #fff;
  margin: 0 150px;
}
.logo-search-nav {
  display: flex;
  align-items: center;
  padding: 5px 0;
  background-color: #e8e6e2;
}

.logo {
  margin-right: 20px; /* 调整间距 */
  margin-left: 60px;
}

.logo-img {
  height: 70px;
}

.cart-text {
  font-size: 24px;
  font-weight: bold;
  color: #368eba;
}

.icon,
.shop {
  margin-right: 5px;
}
.xia {
  font-size: 10px;
  margin-top: 4px;
  margin-right: 10px;
}

.cart-container {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  width: 888px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.cart-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.cart-controls {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  gap: 10px; /* 确保全选和删除按钮之间有合适的间距 */
}

.cart-controls el-checkbox {
  margin-right: 10px;
}

.cart-controls button {
  margin-left: 10px;
}

.cart-item {
  display: flex;
  align-items: center; /* 确保项目垂直居中 */
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.cart-item img {
  width: 60px;
  height: 60px;
  margin-right: 20px;
}

.details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.item-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 200px; /* 确保动作栏宽度一致 */
}

.item-actions .price {
  font-size: 18px;
  color: #08b0d9;
  margin-right: 20px;
}

.cart-summary {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 10px;
  position: absolute; /* 修改 */
  right: 0; /* 新增，靠近右边 */
  margin-top: 110px;
  margin-right: 88px;
  top: 20px; /* 确保它不被顶部边距影响 */
  width: 320px; /* 调整宽度以适应你的设计 */
}

.summary-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.summary-content {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

.summary-images {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 每行4个 */
  gap: 10px;
  margin-bottom: 10px;
}

.summary-image {
  width: 100%; /* 保持图片比例 */
  border-radius: 10%;
}

.total {
  font-size: 18px;
  font-weight: bold;
  color: #08b0d9;
  margin-bottom: 20px;
}

.checkout-button {
  background-color: #08b0d9;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 100px;
  text-align: center;
}

.custom-input-number {
  display: flex;
  align-items: center;
}

.custom-input-number .el-input-number__decrease,
.custom-input-number .el-input-number__increase {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  color: #333;
  cursor: pointer;
  font-size: 16px;
}

.custom-input-number .el-input-number__decrease {
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.custom-input-number .el-input-number__increase {
  border-left: none;
  border-radius: 0 4px 4px 0;
}

.custom-input-number .el-input-number__input {
  width: 40px;
  height: 28px;
  text-align: center;
  border: 1px solid #ddd;
}
</style>
